package cn.shanke.torrentmanagerserver.controller;

import cn.shanke.torrentmanagerserver.config.AppConfig;
import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@RequestMapping("/resource")
public class ResourceController {

    private final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    public static final String TYPE_TORRENT = "torrent";

    public static final String TORRENT_FILE_FOLDER = "torrents";

    @Resource
    private AppConfig appConfig;

    @PostMapping("/upload")
    public ResponseModel upload(@RequestParam("file")MultipartFile file, @RequestParam String type){
        System.out.println(type);
        return saveFile(file, type);
    }
    @PostMapping("/multiUpload")
    public ResponseModel multiUpload(@RequestParam("file")MultipartFile[] files, @RequestParam String type){
        System.out.println("文件的个数:"+files.length);
        for (MultipartFile f : files){
            saveFile(f, type);
        }
        return ResponseModel.success();
    }

    private ResponseModel saveFile(MultipartFile file, String type){
        if (file.isEmpty()){
            return ResponseModel.failure("请选择上传文件");
        }
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称
        Path target = Paths.get(appConfig.getLocation());

        if (TYPE_TORRENT.equals(type)) {
            target = target.resolve(TORRENT_FILE_FOLDER);
        }
        target = target.resolve(filename);

//        if (Files.exists(target)) {
//            return ResponseModel.failure("文件已存在");
//        }
        try {
            if (Files.notExists(target.getParent())) {
                Files.createDirectories(target.getParent());
            }
            Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
//            file.transferTo(target);
        }catch (IOException e){
//            e.printStackTrace();
            logger.error("上传失败：" + e.getMessage());
            return ResponseModel.failure(e.getMessage());
        }

        return ResponseModel.success().data(new JSONObject().fluentPut("name", filename));
    }


    @GetMapping(value = "/download")
    public byte[] downloadLocal(HttpServletResponse response
            , @RequestParam String name
            , @RequestParam String type
    ) throws IOException {

        Path filePath = Paths.get(appConfig.getLocation());
        if (TYPE_TORRENT.equals(type)) {
            filePath = filePath.resolve(TORRENT_FILE_FOLDER);
        }

        filePath = filePath.resolve(name);


        if (Files.notExists(filePath)) {
            response.getWriter().print("file not found");
            return null;
        }
//        // 读到流中
//        InputStream inStream = new FileInputStream(filePath.toFile());
//        // 设置输出的格式
//        response.reset();
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "GET");
//        response.setHeader("Access-control-Allow-Origin", "*");
//        response.setContentType("application/octet-stream");
//        response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(name.getBytes(), "ISO-8859-1") + "\"");
//        // 循环取出流中的数据
//        byte[] b = new byte[1024];
//        int len;
//        try {
//            while ((len = inStream.read(b)) > 0)
//                response.getOutputStream().write(b, 0, len);
//            inStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println(filePath.toFile().getAbsolutePath());
        return Files.readAllBytes(filePath);
    }
}
